package com.edu.course.service.impl;


import com.alibaba.druid.support.json.JSONUtils;
import com.edu.course.mapper.HfdClassInfoMapper;
import com.edu.course.service.IHfdClassInfoService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.edu.entity.HfdClassInfo;

import com.edu.utils.JsonUtils;
import com.edu.vo.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.BoundHashOperations;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

/**
 * <p>
 * 班级表 服务实现类
 * </p>
 *
 * @author jr
 * @since 2021-04-14
 */
@Service
public class HfdClassInfoServiceImpl extends ServiceImpl<HfdClassInfoMapper, HfdClassInfo> implements IHfdClassInfoService {


    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    @Override
    public List<HfdClassInfo> findClassInfo() {

        BoundHashOperations<String, Object, Object> ops = stringRedisTemplate.boundHashOps("hot:pro");

        List<Object> values = ops.values();

        List<HfdClassInfo> classInfo = new ArrayList<>();

        if (values == null || values.size()==0) {

            List<HfdClassInfo> pros = new ArrayList<>();

            synchronized (this) {
                //从redis中获取

                List<Object> valuesAgain = ops.values();

                if(valuesAgain ==null ||valuesAgain.size()==0){
                    //如果redis中没有，从数据库中获取，
                    System.out.println("从数据库中获取");

                    //get from db
                    pros = baseMapper.findClassInfo();

                    //缓存一份到redis
                    pros.forEach(pro->{
                        ops.put(pro.getClassId()+"", JsonUtils.toString(pro));
                    });
                }else{
                    System.out.println("从redis中获取");
                    for (Object value : valuesAgain) {
                        HfdClassInfo hfdClassInfo = JsonUtils.toBean((String) value, HfdClassInfo.class);
                        pros.add(hfdClassInfo);
                    }
                }
            }
            return pros;

        }else{
            //如果redis中有，直接返回
            System.out.println("从redis中获取");
            for (Object value : values) {
                HfdClassInfo hfdClassInfo = JsonUtils.toBean((String) value, HfdClassInfo.class);
                classInfo.add(hfdClassInfo);
            }

            return classInfo;
        }


    }

//    @Override
//    public Result auditCourse(Integer classId) {
//
//        //1.根据id获取课程信息
//        HfdClassInfo hfdClassInfoById = this.baseMapper.findHfdClassInfoById(classId);
//
//        if(hfdClassInfoById == null){
//            return new Result(false , 1 , "改商品不存在");
//        }
//
//        //2 修改商品审核状态
//
//        this.baseMapper.updateById(hfdClassInfoById);
//
//
//        return null;
//    }
}
